package com.eascs.dubbo.api.admin;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.loanapply.CreditQueryService;
import com.eascs.admin.item.service.O2oPubDdItemService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oLoadUserZxServiceImpl;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.entity.O2oZxEntity;
import com.eascs.admin.o2o.zx.from.AddO2oZxForm;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.assertion.exception.WarnAssertionException;
import com.eascs.common.util.StringUtil;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.dubbo.api.util.UserUtils;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@Service
public class CreditQueryServiceImpl implements CreditQueryService {

	private static final Logger logger = LoggerFactory.getLogger(CreditQueryServiceImpl.class);

	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;

	@Autowired
	O2oLoadUserZxServiceImpl o2oLoadUserZxServiceImpl;

	@Autowired
	private O2oDataListService o2oDataListService;

	@Autowired
	O2oPubDdItemService o2oPubDdItemService;

	@Reference
	private WorkFlowService workFlowService;
	
	@Reference
	SysOrgService sysOrgService;

	@Value("${o2o.admin.wf.NewZxUrl}")
	private String NewZxUrl;

	/**
	 * 查询征信信息
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public O2oZxEntity getO2oZxInfo(String id) {
		return o2oZxServiceImpl.getEntityById(id);
	}

	/**
	 * 查询征信客户信息
	 * 
	 * @param id
	 * @return
	 */
	@Override
	public O2oLoanUserEntityZx getO2oLoanUserInfo(String id) {
		return o2oLoadUserZxServiceImpl.getEntityByZxNo(id);
	}

	/**
	 * 启动征信流程
	 * 
	 * @param id
	 * @param materId
	 * @return
	 */
	@Override
	public String startCreditFlow(String id, String materId) {
		
		O2oZxEntity o2oZxEntity = o2oZxServiceImpl.getEntityById(id);
		logger.info("贷款对象：{}", o2oZxEntity);
		O2oLoanUserEntityZx o2oLoanUserEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(id);
		if (!o2oDataListService.checkDataCode(o2oZxEntity.getId(), null)) {
			return "2";
		}
//		if ("ZX_JKR".equals(o2oZxEntity.getZxType()) && "SPDBGZ".equals(o2oZxEntity.getZxBank())) {
//			if (!o2oDataListService.checkPFDataCode(o2oZxEntity.getId())) {
//				return "2";
//			}
//		}
		if (StringUtil.isBlank(o2oZxEntity.getZxBank())) {
			return "4";
		}
		if(!StatusContexts.O2O_BANKTYPE_BC.equals(o2oZxEntity.getZxBank())){
			Boolean isMothSelected =o2oZxServiceImpl.isMothSelectedZX(o2oLoanUserEntityZx.getDocumentNo(), o2oZxEntity.getZxBank());
			if(isMothSelected){
				return "5";
			}
		}
		boolean checkDataCode = o2oDataListService.checkDataCode(id, materId); // check申请材料是否上传齐全。
		if (checkDataCode) {
			WFRequestParam param = new WFRequestParam();
			param.setReferId(o2oZxEntity.getId());
			param.setReferCode(o2oZxEntity.getBillCode());
			param.setReferUrl(NewZxUrl);
			param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
			param.setProcessType(StatusContexts.WF_TYPE_CREDIT_INQUIRY);
			param.setProcessVersion("v1");
			User user = UserHolder.getUser();
			param.setAppliedby(user.getNo());
			param.setAppliedbyName(user.getCname());
			param.setOrgNo(o2oZxEntity.getLtd());
			param.setLoginUser(UserUtils.getUser(user));
			StringBuffer appliedDes = new StringBuffer("姓名:");
			appliedDes.append(o2oLoanUserEntityZx.getUserFullName());
			appliedDes.append("，客户类型:" + o2oPubDdItemService.findPubdditemO2ONameByCode("ZX_TYPE", o2oZxEntity.getZxType()));
			appliedDes.append("，征信银行:" + o2oPubDdItemService.findPubdditemNameByCodeisall("BANKTYPEO2O", o2oZxEntity.getZxBank()));
			param.setAppliedDes(appliedDes.toString());
			logger.info("提交征信，参数有征信id：【{}】，征信编号：【{}】，系统模块：【{}】，流程类型：【{}】，经营平台id：【{}】，贷款摘要信息：【{}】", o2oZxEntity.getId(), o2oZxEntity.getBillCode(), ProcessTemplate.SYSTEM_MODULE_O2O, param.getProcessType(), o2oZxEntity.getLtd(), appliedDes.toString());
			ModelResult<Boolean> modelResult = workFlowService.instance(param);
			if (modelResult.isSuccess() && modelResult.getModel()) {
				o2oZxEntity.setZxStatus(StatusContexts.WFTYPE_STATUS_RUN);
				o2oZxEntity.setSubmitId(user.getNo());
				o2oZxEntity.setSubmitName(user.getCname());
				o2oZxEntity.setSubmitDate(new Date());
				o2oZxServiceImpl.update(o2oZxEntity);
				return "1";
			} else {
				logger.error("提交征信失败，错误信息{}", modelResult.getDetailStack());
			}
		} else {
			return "3";
			//throw new WarnAssertionException("附件上传未齐全,请编辑贷款信息");
		}
		return materId;
	}

	/**
	 * 保存征信信息
	 * 
	 * @param addO2oZxForm
	 * @return
	 */
	@Override
	public int updateCreditInfo(AddO2oZxForm addO2oZxForm) {
		logger.info("修改addO2oZxForm=={}", addO2oZxForm.toString());
		ActOrgEntity actOrgEntity = null;
		actOrgEntity = sysOrgService.getOrgByUnitNo(addO2oZxForm.getLtd());
		O2oZxEntity o2oZxEntity = null;
		if (addO2oZxForm.getId() != null) {
			o2oZxEntity = o2oZxServiceImpl.getEntityById(addO2oZxForm.getId());
		} else {
			throw new WarnAssertionException("未找到该征信单的id");
		}

		if (o2oZxEntity == null) {
			throw new WarnAssertionException("系统中未找到该征信单的信息，请联系管理员");
		}
		
		O2oLoanUserEntityZx o2oLoanUserEntityZx = o2oLoadUserZxServiceImpl.getEntityByZxNo(addO2oZxForm.getId());
		if (!StatusContexts.O2O_BANKTYPE_BC.equals(addO2oZxForm.getZxBank())) {
			Boolean isMothSelected = o2oZxServiceImpl.isMothSelectedZX(o2oLoanUserEntityZx.getDocumentNo(), addO2oZxForm.getZxBank());
			if (isMothSelected) {
				throw new WarnAssertionException("一个自然月内在同一家银行仅能查询一次个人征信报告");
			}
		}
		
		o2oZxEntity.setIsDel(StatusContexts.O2O_NO);
		o2oZxEntity.setLtd(addO2oZxForm.getLtd());
		o2oZxEntity.setZxStatus(StatusContexts.O2O_NEW);
		o2oZxEntity.setLtdName(actOrgEntity.getOrgName());
		o2oZxEntity.setLtdCode(actOrgEntity.getUnitCode());
		o2oZxEntity.setOperatorId(addO2oZxForm.getOperatorNo());
		o2oZxEntity.setOperatorName(addO2oZxForm.getOperatorName());
		o2oZxEntity.setZxBank(addO2oZxForm.getZxBank());
		o2oZxEntity.setZxType(addO2oZxForm.getZxType());
		return o2oZxServiceImpl.update(o2oZxEntity);
	}

}
